<template>  
  <div>
    <el-row>
      <!--输入文章标题-->
      <el-col :span="20">
        <el-input
          type="text"
          placeholder="请输入文章标题"
          v-model="form.title"
          show-word-limit
        >
        </el-input>
      </el-col> 
      <el-col :span="4">
        <el-button type="success" plain @click="postFormVisible=true">发布</el-button>
      </el-col>
    </el-row>

    <!--文章内容-->
    <mavon-editor class="myClass" ref="md" v-model="form.content" @imgAdd="imgAdd" :toolbars="toolbars"/>

    <!--发布内容弹出框-->
    <el-dialog title="发布博客" :visible.sync="postFormVisible" :modal="false">
      <el-form :model="form">
        <!--分类-->
        <el-form-item label="博客分类" :label-width="formLabelWidth">
          <el-select
            v-model="form.typeId"
            filterable
            allow-create
            placeholder="请选择文章标签">
            <el-option
              v-for="item in types"
              :key="item.value"
              :value="item.id"
              :label="item.name" >
            </el-option>
          </el-select>
        </el-form-item>
        <!--显示选择标签  closable-->
        <el-form-item label="博客标签" :label-width="formLabelWidth">
          <el-tag
            :key="tag"
            v-for="tag in checkedTagsName"
            :disable-transitions="false"
            @close="handleClose(tag)"
            closable>
            {{tag}}
          </el-tag>
          <!-- 标签 -->
          <div class="tags">
            <el-alert
              title="最多选择3个标签"
              type="warning"
              :closable="false"> 
            </el-alert>
            <el-checkbox-group 
              v-model="checkedTags"
              :max="3">
              <el-checkbox v-for="tag in tags" :label="tag.id+','+tag.name" :key="tag.id">{{tag.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <!--文章简介-->
        <el-form-item label="文章简介" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="form.description">
          </el-input>
        </el-form-item>
        <!--文章封面-->
        <!--3.上传图片-->
        <el-form-item label="文章封面" :label-width="formLabelWidth">
          <el-upload
            :data="dataObj"
            action="http://tfblog.oss-cn-hangzhou.aliyuncs.com"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="1">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="this.form.firstPicture" alt="">
          </el-dialog>
          <p>仅允许上传一张</p>
        </el-form-item>
        <el-form-item label="文章选项" :label-width="formLabelWidth">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedOptions" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="opt in options" :label="opt" :key="opt">{{opt}}</el-checkbox>
          </el-checkbox-group>
          <!--转载/原创-->
          <el-radio v-model="form.flag" label="原创">原创</el-radio>
          <el-radio v-model="form.flag" label="转载">转载</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="postFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postArtical('blog')">发布为博客</el-button>
        <el-button type="primary" @click="postArtical('craft')">发布为草稿</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getUUID} from '@/utils/index.js'
  import qs from 'qs'
  export default{
    data(){
      return {
        formLabelWidth: '120px',
        //2.上传图片
        dataObj: {
          policy: "",
          signature: "",
          key: "",
          ossaccessKeyId: "",
          dir: "",
          host: "",
          uuid: "",
        },
        postFormVisible:false,//提交文章框的显示与否
        form: { //提交保单
          title:'',
          content:'',
          typeId:'', //分类
          tags:[],//标签
          description:'',//简介
          firstPicture:'',
          //单选
          flag:'原创',
          published:true,//默认发布
          appreciation:false, //赞赏
          commentabled:false, //评论
          recommend:false, //推荐
          shareStatement:false, //转载
        },
        types: [],//后端获取分类
        tags:[], //后端获取标签
        checkedTags:[],//选中的标签
        checkedTagsName:[],//选中的标签name
        dialogVisible:false, //图片预览
        //文章选项
        options: ['开启赞赏', '开启评论', '开启推荐','开启转载'],
        checkedOptions: [],//选中的文章选项
        checkAll: false, //全选
        isIndeterminate: true,
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: false, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: true, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        },

      }
    },
    created(){
      this.getTypes()
      this.getTags()
      //TODO
      if(this.$route.query.form != null){
        this.checkedOptions = []
        this.form = this.$route.query.form
        if(this.$route.query.form.appreciation){this.checkedOptions.push('开启赞赏')}
        if(this.$route.query.form.commentabled){this.checkedOptions.push('开启评论')}
        if(this.$route.query.form.recommend){this.checkedOptions.push('开启推荐')}
        if(this.$route.query.form.shareStatement){this.checkedOptions.push('开启转载')}
        this.getArticalTags(this.$route.query.form.id)
      }
    },
    watch:{
      checkedOptions:{
        handler(newValue, oldValue){
          this.form.appreciation = newValue.indexOf('开启赞赏') != -1
          this.form.commentabled = newValue.indexOf('开启评论') != -1
          this.form.recommend = newValue.indexOf('开启推荐') != -1
          this.form.shareStatement = newValue.indexOf('开启转载') != -1
        }, 
        deep:true
      },
      checkedTags:{
        handler(newValue, oldValue){
          this.checkedTagsName = []
          this.form.tags = []
          for(let item of newValue){
            let temp = item.split(',')
            this.checkedTagsName.push(temp[1])
            this.form.tags.push(temp[0])
          }
        }, 
        deep:true
      }
    },
    methods:{
      //获取分类
      async getTypes(){
        const {data:res} = await this.$http.get('/blog/type/list')
        this.types = res.data
      },
      //获取标签
      async getTags(){
        const {data:res} = await this.$http.get('/blog/tag/list')
        this.tags = res.data
      },
      //1.上传图片
      async beforeUpload(){
        const {data:response} = await this.$http.post('/thirdparty/oss/policy')
        this.dataObj.policy = response.data.policy;
        this.dataObj.signature = response.data.signature;
        this.dataObj.ossaccessKeyId = response.data.accessid;
        this.dataObj.key = response.data.dir + getUUID() + '_${filename}';
        this.dataObj.dir = response.data.dir;
        this.dataObj.host = response.data.host;     
      },
      handleUploadSuccess(res, file) {
        this.form.firstPicture=this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) 
      },
      handleRemove(file, fileList) {
        this.form.firstPicture = ''
      },
      handlePictureCardPreview(file) {
        this.dialogVisible = true;
      },
      //文章选项
      handleCheckAllChange(val) {
        this.checkedOptions = val ? this.options : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.options.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.options.length;
      },
      //上传博客
      async postArtical(articalType){
        if(articalType == 'blog'){
          this.form.published = true
        }else{
          this.form.published = false
        }
        if(this.form.id != undefined){
          const {data:res} = await this.$http.post('/blog/blogs/update',this.form)
          if(res.meta.status !== 200){
            this.$message({
              type: 'infp',
              message: res.meta.msg
            });  
          }else{
            this.$message({
              type: 'success',
              message: res.meta.msg
            }); 
            this.postFormVisible = false
            this.$router.push('/admin')
          }   
        }else{
          const {data:res} = await this.$http.post('/blog/blogs/save',this.form)
          if(res.meta.status !== 200){
            this.$message({
              type: 'infp',
              message: res.meta.msg
            });  
          }else{
            this.$message({
              type: 'success',
              message: res.meta.msg
            }); 
            this.postFormVisible = false
            this.$router.push('/admin')
          }   
        }  
      },
      //编辑文章时获取该文章的标签
      async getArticalTags(id){
        const {data:res} = await this.$http.get('/blog/blogs/types/'+id)
        this.checkedTags = []
        console.log(res.data)
        for(let item of res.data){
          this.checkedTags.push(item.id+','+item.name)
        }
      },
      //添加标签删除功能
      handleClose(tag) {
        for(let i = 0; i < this.checkedTags.length; i++){
          let tempArr = this.checkedTags[i].split(',')
          if(tempArr[1] == tag){
            this.checkedTags.splice(i, 1)
            return
          }
        }
      },

      //markdown方法
      uploadFile(formData){
        return this.$http({
          method: 'post',
          url: `http://tfblog.oss-cn-hangzhou.aliyuncs.com`,
          data: this.dataObj,
          processData:false,//这里默认为true,必须手动改为false
          contentType:false,//这里必须手动改为false,避免出现解析错误
        });   
      },
      async imgAdd(pos,$file){
        console.log(pos)
        console.log($file)
        //1.获取阿里云的账号        
        const {data:response} = await this.$http.post('/thirdparty/oss/policy')
        this.dataObj.policy = response.data.policy;
        this.dataObj.signature = response.data.signature;
        this.dataObj.ossaccessKeyId = response.data.accessid;
        this.dataObj.key = response.data.dir + getUUID() + '_${filename}';
        this.dataObj.dir = response.data.dir;
        this.dataObj.host = response.data.host;  

       
        var formData = new FormData()
        formData.append('policy', this.dataObj.policy)   
        formData.append('signature', this.dataObj.signature)   
        formData.append('ossaccessKeyId', this.dataObj.ossaccessKeyId)   
        formData.append('key', this.dataObj.key)   
        formData.append('dir', this.dataObj.dir)   
        formData.append('host', this.dataObj.host)  
        formData.append('uuid', '')  
        formData.append('file', $file)
        const res = await this.$http.post('http://tfblog.oss-cn-hangzhou.aliyuncs.com',formData) 


        // this.uploadFile(formData).then(res => {
        //   if (resp.status == 200) {
        //     let url = this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) 
        //     _this.$refs.md.$img2Url(pos, url)
        //   } else {
        //     _this.$message({type: resp.status, message: resp.statusText});
        //   }
        // })

        let url = this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",$file.name) 
        this.$refs.md.$img2Url(pos, url)

      }
    }
  }
</script>

<style scoped>
  .el-row{
    margin-bottom:30px;
  }
  .el-col{
    text-align:center;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .tags{
    padding-bottom:15px;
    border: 1px solid #DCDFE6;
    border-radius:5px;
  }
  .el-alert{
    height:35px;
  }
  .el-checkbox-group {
    padding-left:8px;
    padding-bottom:15px;
  }


  .myClass{
    height:1000px !important;
  }

</style>